package com.xatl.simulated.client;

import com.xatl.simulated.constant.MqttPropertiesUtils;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Slf4j
@Component
public class MyMqttClient {

    @Autowired
    private MqttPropertiesUtils MqttProperties;

    MqttClient init(String clientId) {
        MqttClient mqttClient = null;
        if (null != clientId) {
            try {
                log.info("Start to init param MqttClient! client id is {}", clientId);
                mqttClient = new MqttClient(MqttProperties.getHost(), clientId, new MemoryPersistence());
                // 建立连接
                mqttClient.connect(this.setMqttConnectOptions());
                log.info("Success to init param MqttClient!");
            } catch (MqttException e) {
                log.error("Link paho error. Cause by {}", e.getCause());
            }
        } else {
            log.error("mqttConnectOptions对象为空");
        }

        return mqttClient;
    }

    private MqttConnectOptions setMqttConnectOptions() {
        // 初始化连接设置对象
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        // true可以安全地使用内存持久性作为客户端断开连接时清除的所有状态
        mqttConnectOptions.setCleanSession(true);
        // 设置连接的用户名
        mqttConnectOptions.setUserName(MqttProperties.getUsername());
        // 设置连接的密码
        mqttConnectOptions.setPassword(MqttProperties.getPassword().toCharArray());
        // 设置超时时间 单位为秒
        mqttConnectOptions.setConnectionTimeout(MqttProperties.getTimeout());
        // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
        mqttConnectOptions.setKeepAliveInterval(MqttProperties.getInterval());
        // 设置断开后重新连接
        mqttConnectOptions.setAutomaticReconnect(true);

        log.info("Success to reset mqtt connect options client!");
        return mqttConnectOptions;
    }
}
